package com.car.shopping.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.car.shopping.controller.form.AddGoodsInfoForm;
import com.car.shopping.controller.form.FindGoodsForPageForm;
import com.car.shopping.entity.GoodsInfo;
import com.car.shopping.entity.GoodsModifyLog;
import com.car.shopping.mapper.GoodsInfoMapper;
import com.car.shopping.mapper.GoodsModifyLogMapper;
import com.car.shopping.service.GoodsInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.car.shopping.service.dto.AddGoodsInfoDto;
import com.car.shopping.service.dto.GoodsDto;
import com.car.shopping.service.dto.GoodsInfoDto;
import com.car.shopping.service.param.AddGoodsInfoParam;
import com.car.shopping.service.param.ModifyGoodsInfoParam;
import com.car.shopping.util.OSSUtil;
import org.apache.tika.Tika;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 董旭
 * @since 2024-08-28
 */
@Service
public class GoodsInfoServiceImpl extends ServiceImpl<GoodsInfoMapper, GoodsInfo> implements GoodsInfoService {
    @Autowired
    private GoodsModifyLogMapper goodsModifyLogMapper;

    @Autowired
    private GoodsInfoMapper goodsInfoMapper;

    @Resource
    private OSSUtil ossUtil;

    private static final Tika tika = new Tika();





    @Override
    public List<GoodsInfoDto> findGoodsInfoListByIds(Set<Integer> ids) {
        List<GoodsInfo> goodsInfoList = this.listByIds(ids);  // 使用 MyBatis-Plus 提供的 listByIds 方法

        // 将 GoodsInfo 实体转换为 GoodsInfoDto
        List<GoodsInfoDto> goodsInfoDtoList = goodsInfoList.stream()
                .map(goodsInfo -> {
                    GoodsInfoDto dto = new GoodsInfoDto();
                    dto.setGoodsId(goodsInfo.getGoodsId());
                    dto.setGoodsName(goodsInfo.getGoodsName());
                    dto.setGoodsState(goodsInfo.getGoodsState());
                    dto.setGoodsStock(goodsInfo.getGoodsStock());
                    dto.setGoodsTypeId(goodsInfo.getGoodsTypeId());
                    dto.setGoodsPrice(goodsInfo.getGoodsPrice());
                    dto.setGoodsImg(goodsInfo.getGoodsImg());
                    return dto;
                })
                .collect(Collectors.toList());
        return goodsInfoDtoList;
    }


    @Override
    public void updateGoodsStock(Set<GoodsDto> goods) {
        for (GoodsDto goodsDto : goods) {
            // 查找商品信息
            GoodsInfo goodsInfo = this.getById(goodsDto.getGoodsId());
            if (goodsInfo != null) {
                // 更新库存量和冻结量
                goodsInfo.setGoodsStock(goodsInfo.getGoodsStock() - goodsDto.getGoodsCont());
                //增加冻结量
                goodsInfo.setGoodsFreeze(goodsInfo.getGoodsFreeze()+goodsDto.getGoodsCont());
                // 保存更新后的商品信息
                this.updateById(goodsInfo);
            }
        }
    }

    @Override
    public AddGoodsInfoForm addGoods(AddGoodsInfoParam addGoodsInfoParam, Integer adminId) throws Exception{
        // 创建 GoodsInfo 实体并填充数据
        GoodsInfo goodsInfo = new GoodsInfo();
        goodsInfo.setGoodsName(addGoodsInfoParam.getGoodsName());
        goodsInfo.setGoodsTypeId(addGoodsInfoParam.getGoodsTypeId());
        goodsInfo.setGoodsStock(addGoodsInfoParam.getGoodsStock());
        goodsInfo.setGoodsPrice(addGoodsInfoParam.getGoodsPrice());
        goodsInfo.setGoodsDetail(addGoodsInfoParam.getGoodsDetail());
        goodsInfo.setGoodsState(1);
        goodsInfo.setAdminId(adminId);
        goodsInfo.setModifyTime(LocalDateTime.now());

        // 处理商品图片
         MultipartFile file = addGoodsInfoParam.getGoodsImg();
        if (!isImage(file)) {
            throw new Exception("上传到不是图片");
        }
        InputStream fileContent = file.getInputStream(); // 文件输入流
        String oldName = addGoodsInfoParam.getGoodsImg().getOriginalFilename();
        String suffix = oldName.substring(oldName.lastIndexOf("."));
        String ImgUrl = ossUtil.uploadFile(fileContent, UUID.randomUUID() + suffix, "ootaoyuoo");
        goodsInfo.setGoodsImg(ImgUrl);

            // 保存商品信息到数据库
            this.save(goodsInfo);

            // 保存修改日志到 GoodsModifyLog 表
            GoodsModifyLog log = new GoodsModifyLog();
            log.setAdminId(adminId);
            log.setGoodsId(goodsInfo.getGoodsId());
            log.setModifyTime(LocalDateTime.now());
            goodsModifyLogMapper.insert(log);

            // 创建并返回 AddGoodsInfoDto
            AddGoodsInfoForm addGoodsInfoForm = new AddGoodsInfoForm();
            addGoodsInfoForm.setGoodsName(goodsInfo.getGoodsName());
            addGoodsInfoForm.setGoodsTypeId(goodsInfo.getGoodsTypeId());
            addGoodsInfoForm.setGoodsStock(goodsInfo.getGoodsStock());
            addGoodsInfoForm.setGoodsPrice(goodsInfo.getGoodsPrice());
            addGoodsInfoForm.setGoodsDetail(goodsInfo.getGoodsDetail());
            addGoodsInfoForm.setGoodsImg(goodsInfo.getGoodsImg());

            return addGoodsInfoForm;
        }

    @Override
    public Page<GoodsInfo> findGoodsForPage(FindGoodsForPageForm form) {
        QueryWrapper<GoodsInfo> queryWrapper = new QueryWrapper<>();
        //lambda效果
        //queryWrapper.like("goods_name", "%apple%");   queryWrapper.lambda().like(GoodsInfo::getGoodsName, "%apple%");
        //名字不为空则添加模糊匹配查询条件
        if (form.getGoodsName() != null && !form.getGoodsName().isEmpty()) {
            queryWrapper.lambda().like(GoodsInfo::getGoodsName, form.getGoodsName());
        }

        if (form.getGoodsTypeId() != null) {
            queryWrapper.lambda().eq(GoodsInfo::getGoodsTypeId, form.getGoodsTypeId());
        }

        Page<GoodsInfo> page = new Page<>(form.getPageNum(), form.getPageSize());
        return this.page(page, queryWrapper);
    }

    @Override
    public void modifyGoods(ModifyGoodsInfoParam modifyGoodsInfoParam, Integer adminId) {
        // 查找商品信息
        GoodsInfo goodsInfo = this.getById(modifyGoodsInfoParam.getGoodsId());
        if (goodsInfo == null) {
            throw new RuntimeException("商品不存在");
        }

        // 更新商品信息,仅更新传递了新值的字段
        if (modifyGoodsInfoParam.getGoodsName() != null && !modifyGoodsInfoParam.getGoodsName().isEmpty()) {
            goodsInfo.setGoodsName(modifyGoodsInfoParam.getGoodsName());
        }

        if (modifyGoodsInfoParam.getGoodsTypeId() != null) {
            goodsInfo.setGoodsTypeId(modifyGoodsInfoParam.getGoodsTypeId());
        }

        if (modifyGoodsInfoParam.getGoodsStock() != null) {
            goodsInfo.setGoodsStock(modifyGoodsInfoParam.getGoodsStock());
        }

        if (modifyGoodsInfoParam.getGoodsPrice() != null) {
            goodsInfo.setGoodsPrice(modifyGoodsInfoParam.getGoodsPrice());
        }

        if (modifyGoodsInfoParam.getGoodsDetail() != null && !modifyGoodsInfoParam.getGoodsDetail().isEmpty()) {
            goodsInfo.setGoodsDetail(modifyGoodsInfoParam.getGoodsDetail());
        }

        // 更新操作的管理员 ID 和修改时间
        goodsInfo.setAdminId(adminId);
        goodsInfo.setModifyTime(LocalDateTime.now());

        // 处理商品图片（如果有上传新图片）
        MultipartFile goodsImg = modifyGoodsInfoParam.getGoodsImg();
        if (goodsImg != null && !goodsImg.isEmpty()) {
            try {
                if (!isImage(goodsImg)) {
                    throw new RuntimeException("上传的文件不是图片");
                }
                InputStream fileContent = goodsImg.getInputStream();
                String oldName = goodsImg.getOriginalFilename();
                String suffix = oldName.substring(oldName.lastIndexOf("."));
                String imgUrl = ossUtil.uploadFile(fileContent, UUID.randomUUID() + suffix, "ootaoyuoo");
                goodsInfo.setGoodsImg(imgUrl);
                System.out.println("图片"+imgUrl);
            } catch (Exception e) {
                throw new RuntimeException("图片上传失败", e);
            }
        }
        // 保存修改后的商品信息
        this.updateById(goodsInfo);

        // 保存修改日志到 GoodsModifyLog 表
        GoodsModifyLog log = new GoodsModifyLog();
        log.setAdminId(adminId);
        log.setGoodsId(goodsInfo.getGoodsId());
        log.setModifyTime(LocalDateTime.now());
        goodsModifyLogMapper.insert(log);
    }

    @Override
    public void addStock(Set<GoodsDto> goods) {
        for (GoodsDto dto : goods) {
            // 查找商品信息
            GoodsInfo goodsInfo = goodsInfoMapper.selectById(dto.getGoodsId());
            if (goodsInfo != null) {
                // 增加库存量
                goodsInfo.setGoodsStock(goodsInfo.getGoodsStock() + dto.getGoodsCont());
                // 更新商品信息
                goodsInfoMapper.updateById(goodsInfo);
            }
        }
    }

    @Override
    public void addStockAndReduceFreezeStock(Set<GoodsDto> goods) {
        for (GoodsDto dto : goods) {
            // 查找商品信息
            GoodsInfo goodsInfo = goodsInfoMapper.selectById(dto.getGoodsId());
            if (goodsInfo != null) {
                // 增加库存量
                goodsInfo.setGoodsStock(goodsInfo.getGoodsStock() + dto.getGoodsCont());
                // 减少冻结量
                goodsInfo.setGoodsFreeze(goodsInfo.getGoodsFreeze() - dto.getGoodsCont());
                // 更新商品信息
                goodsInfoMapper.updateById(goodsInfo);
            }
        }
    }

    @Override
    public void reduceFreezeStock(Set<GoodsDto> goods) {
        for (GoodsDto dto : goods) {
            // 查找商品信息
            GoodsInfo goodsInfo = goodsInfoMapper.selectById(dto.getGoodsId());
            if (goodsInfo != null) {
                // 减少冻结量
                goodsInfo.setGoodsFreeze(goodsInfo.getGoodsFreeze() - dto.getGoodsCont());
                // 更新商品信息
                goodsInfoMapper.updateById(goodsInfo);
            }
        }
    }

    @Override
    public void reduceStock(Set<GoodsDto> goodsDtos) {
        for (GoodsDto dto : goodsDtos) {
            // 根据id查找商品信息
            GoodsInfo goodsInfo = goodsInfoMapper.selectById(dto.getGoodsId());
            if (goodsInfo != null) {
                // 减少库存量
                goodsInfo.setGoodsStock(goodsInfo.getGoodsStock() - dto.getGoodsCont());
                // 更新商品信息
                goodsInfoMapper.updateById(goodsInfo);
            }
        }
    }

    @Override
    public List<GoodsInfo> findAll() throws Exception {
        return this.list();
    }

    @Override
    public GoodsInfo findGoodsById(Integer id) throws Exception {
        return this.getById(id);  // 调用 BaseMapper 的 getById 方法
    }

    @Override
    public void state(Integer goodsId) throws Exception {
        // 查询商品信息
        GoodsInfo goodsInfo = goodsInfoMapper.selectById(goodsId);

        if (goodsInfo == null) {
            throw new Exception("商品未找到");
        }

        // 根据当前状态更新状态
        Integer currentState = goodsInfo.getGoodsState();
        Integer newState = (currentState == 1) ? 2 : 1;

        // 创建更新条件
        UpdateWrapper<GoodsInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("goods_id", goodsId)
                .set("goods_state", newState);

        // 执行更新操作
        goodsInfoMapper.update(null, updateWrapper);
    }


    //判断是否是图片的方法
    private boolean isImage(MultipartFile file) throws Exception {
        String mimeType = tika.detect(file.getInputStream());
        return mimeType != null && mimeType.startsWith("image");
    }

}
